package com.th.coupon.controller;

import com.th.coupon.common.exception.BaseCloudException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 健康检查接口
 * @author 涂航
 */
@Slf4j
@RestController
public class HealthCheck {

    /**
     * 服务发现客户端
     */
    private final DiscoveryClient discoveryClient;
    /**
     * 服务注册接口，提供获取服务id的方法
     */
    private final Registration registration;


    @Autowired
    public HealthCheck(DiscoveryClient discoveryClient, Registration registration) {
        this.discoveryClient = discoveryClient;
        this.registration = registration;
    }

    /**
     * 获取eureka server 上的微服务元信息
     *  url(127.0.0.1:7001/coupon-template/info)
     * @return {@link List}
     */
    @GetMapping("/info")
    public List<Map<String,Object>> info(){
        //大约需要等待两分钟时间才能获取到注册信息
        List<ServiceInstance> instances = discoveryClient.getInstances(registration.getServiceId());

        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        instances.forEach(instance ->{
            Map<String,Object> info = new HashMap<>();
            info.put("serviceId",instance.getServiceId());
            info.put("instance",instance.getInstanceId());
            info.put("port",instance.getPort());
            result.add(info);
        });
        return result;
    }




    /**
     * 健康检查接口
     * url(127.0.0.1:7001/coupon-template/health)
     * url(127.0.0.1:10011/discount/coupon-template/health) 网关API
     * @return {@link String}
     */
    @GetMapping("/health")
    public String health(){
        log.debug("view health api !!!");
        return "CouponTemplate IS O !!!";
    }

    /**
     * 异常测试接口
     * url(127.0.0.1:7001/coupon-template/exception)
     * @return {@link String}
     * @throws BaseCloudException
     */
    @GetMapping("/exception")
    public String exception() throws BaseCloudException {
        log.debug("view health api !!!");
        throw new BaseCloudException("CouponTemplate Has Some Problem !!!");
    }



}
